package com.hhd.form.component;

import com.hhd.base.utils.CommonUtils;
import com.hhd.form.entity.DesignFormFieldDefinition;
import com.hhd.form.entity.DesignFormTableFieldMeta;
import com.hhd.form.entity.DesignFormTableMeta;
import com.hhd.form.table.field.TableFieldDefinition;
import com.hhd.form.vo.FormDefinition;

import java.util.List;

public abstract class AbstractFieldComponent implements FieldComponent {
    @Override
    public List<TableFieldDefinition> createField(DesignFormFieldDefinition field,
                                                  DesignFormTableFieldMeta fieldMeta,
                                                  FormDefinition fomDefinition,
                                                  DesignFormTableMeta tableMeta) {
        List<TableFieldDefinition> res = CommonUtils.newList();
        resolveFieldLength(field, fieldMeta);
        TableFieldDefinition tableField = createMainField(field, fieldMeta);

        if (this.hasTitleField()) {
            res.add(createTitleField(field));
        }

        res.add(tableField);
        fieldMeta.setFieldType(getDBType(field).toString());
        fieldMeta.setLength(field.getLength());
        return res;
    }

    protected void resolveFieldLength(DesignFormFieldDefinition field, DesignFormTableFieldMeta fieldMeta) {

    }

    protected TableFieldDefinition createTitleField(DesignFormFieldDefinition field) {
        TableFieldDefinition tableField = new TableFieldDefinition();

        if (!CommonUtils.isEmpty(field.getFieldTitleName())) {
            tableField.setFieldName(field.getFieldName() + "_title");
        }
        tableField.setComment(field.getRemark());
        tableField.setDbType(ComponentDBFieldType.string);
        tableField.setLength(field.getLength());
        onCreateMainField(field, tableField);
        return tableField;
    }

    protected boolean hasTitleField() {
        return false;
    }

    protected TableFieldDefinition createMainField(DesignFormFieldDefinition field, DesignFormTableFieldMeta fieldMeta) {
        TableFieldDefinition tableField = new TableFieldDefinition();
        tableField.setFieldName(field.getFieldName());
        tableField.setComment(field.getLabel());
        tableField.setDbType(this.getDBType(field));
        tableField.setLength(field.getLength());
        onCreateMainField(field, tableField);
        return tableField;
    }

    protected void onCreateMainField(DesignFormFieldDefinition field, TableFieldDefinition tableField) {
    }

    public abstract ComponentDBFieldType getDBType(DesignFormFieldDefinition field);
}
